package distrcomp;

import java.io.InputStream;
import java.io.StringWriter;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RemoteServer;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;

import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

public class RegistryImpl extends UnicastRemoteObject implements MyRegistry {
	private static final long serialVersionUID = 1L;
	private HashMap<String, Service> services;
	
	//Constructor
	protected RegistryImpl() throws RemoteException {
		super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory(null, null, true));
		this.services = new HashMap<String, Service>();
	}

	//Bind-method
	public boolean bind(String serviceName, Remote service) throws RemoteException {
		//Verify that no such service already exists
		if(!this.services.containsKey(serviceName)) {
			try {
				Service serv = new Service(RemoteServer.getClientHost());
				Registry registry = LocateRegistry.getRegistry(null, 1099, new SslRMIClientSocketFactory());
				registry.bind(serviceName, service);
				this.services.put(serviceName, serv);
				return true;
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	//Rebind method
	public boolean reBind(String serviceName, Remote service) throws RemoteException {
		try {
			//Check if the service exists and if so, whether the client is the owner of the service
			if(this.services.containsKey(serviceName) && (this.services.get(serviceName).getClient() == RemoteServer.getClientHost())) {
				Registry registry = LocateRegistry.getRegistry(null, 1099, new SslRMIClientSocketFactory());
				registry.rebind(serviceName, service);
				return true;
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	//Unbind-method
	public boolean unBind(String serviceName, Remote service) throws RemoteException {
		try {
			//Check if the service exists and if so, whether the client is the owner of the service
			if(this.services.containsKey(serviceName) && (this.services.get(serviceName).getClient() == RemoteServer.getClientHost())) {
				Registry registry = LocateRegistry.getRegistry(null, 1099, new SslRMIClientSocketFactory());
				registry.unbind(serviceName);
				this.services.remove(serviceName);
				return true;
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
